<?php

namespace app\api\controller\web;

use app\admin\model\apply\Confg;
use app\admin\model\apply\Video;
use app\admin\model\memberpoint\Integral;
use app\admin\model\nursery\Companyattestation;
use app\admin\model\nursery\NurserySell;
use app\admin\model\nursery\NurseryWantbuyOffer;
use app\admin\model\nursery\Specs;
use app\admin\model\nursery\Wantbuy;
use app\admin\model\Type;
use app\api\controller\server\Server;
use app\common\controller\Api;
use app\common\helpers\ImageUtil;
use app\common\model\Attachment;
use app\common\model\ScoreLog;
use app\common\model\User;
use fast\Tree;
use think\Cache;
use think\Db;
use think\Exception;
use think\exception\ValidateException;
use think\Log;
use think\Model;
use think\Request;
use think\Validate;


class Index extends Api
{
    protected $noNeedLogin = ['typeList','specsList','supplyList','cs','getNameList'];
    protected $noNeedRight = '*';
    protected $model ='';
    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 用于把大于300k 的图片跑车缩略图
     */
    public function cs(){
        $small = 'small';
        $list = Db::name('nursery_sell')->alias('c')
            ->where('is_sx','1')
            ->limit(1,50)
            ->select();
        if($list){
            foreach ($list as $v){
                if($v['imgs']){
                    $arrImg = explode(',',$v['imgs']);

                    $imgList =  Db::name('attachment')
                        ->field('imagewidth,imageheight,filesize,url,imagetype')
                        ->where('imagetype','in',['png','jpg','webp','jpeg'])
                        ->where('filesize','>',300000)
                        ->where('url','in',$arrImg)
                        ->select();

                    if($imgList){
                        foreach ($imgList as $params){
                            if($params['filesize']>300000){
                                //横图＝宽比高大
                                if($params['imagewidth']>=$params['imageheight']){
                                    if($params['imagewidth']>=810){
                                        $width = 810;
                                        $height = round($params['imageheight']/($params['imagewidth']/810));
                                    }else{
                                        $width = $params['imagewidth'];
                                        $height = $params['imageheight'];
                                    }
                                }else{//坚图＝高比宽大
                                    if($params['imageheight']>=540){
                                        $height = 540;
                                        $width = round($params['imagewidth']/($params['imageheight']/540));
                                    }else{
                                        $width = $params['imagewidth'];
                                        $height = $params['imageheight'];
                                    }
                                }

                                $pathname = $params['url'];
                                $file = ROOT_PATH . 'public'.$pathname;


                                if($small){
                                    $pathname = str_replace('.'.$params['imagetype'],'_'.$small.'.'.$params['imagetype'],$pathname); ;
                                }

                                //                    $file = $this->file;
                                if (!file_exists(ROOT_PATH . 'public'.$pathname)) {
                                    $image = \think\Image::open($file);
                                    $image->thumb($width, $height)->save('.' . $pathname);
                                }

                            }
                        }

                        Db::name('nursery_sell')->where('id',$v['id'])->update(['is_sx'=>2]);
                    }else{
                        Db::name('nursery_sell')->where('id',$v['id'])->update(['is_sx'=>3]);
                    }
                }else{
                    Db::name('nursery_sell')->where('id',$v['id'])->update(['is_sx'=>4]);
                }


            }
        }
    }

    /**
     * 分类列表
     */
    public function typeList()
    {
        $list =  Db::name('type')->field('id,pid,name')->where(['lvl'=>1,'status'=>'normal'])->select();
        if($list){
            $lvl2 =  Db::name('type')->field('id,pid,name')->where(['lvl'=>2,'status'=>'normal'])->select();
            $lvl3 =  Db::name('type')->field('id,pid,name')->where(['lvl'=>3,'status'=>'normal'])->select();
            foreach ($list as &$v){
                foreach ($lvl2 as &$v2){
                    if($v['id'] == $v2['pid']){
                        foreach ($lvl3 as $v3){
                            if($v2['id'] == $v3['pid']){
                                $v2['childs'][]= $v3;
                            }
                        }
                        $v['childs'][]= $v2;
                    }
                }
            }
        }
        $this->success("获取成功",$list);;
    }

    /**
     * 规格列表
     */
    public function specsList()
    {
        $list = (new Specs())->where('status',1)->order('sort desc')->select();
        if($list){
            foreach ($list as &$v){
                if($v['type'] == 'select'){
                    $v['json_value_arr'] = $v['json_value'] ? explode(',',$v['json_value']) :[];
                }
            }
        }
        $this->success('请求成功',$list);
    }

    /**
     * 供应列表
     */
    public function supplyList()
    {
        $type = $this->request->param('type',1);
        $search_name = $this->request->param('search_name');
        $lng = $this->request->param('lng');
        $lat = $this->request->param('lat');
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $user_id = $this->request->param('user_id');
        $where = [
            'ns.status'=>'1',
            'u.status'=>'normal'
        ];
        $province_id = $this->request->param('province_id');
        $city_id = $this->request->param('city_id');
        $county_id = $this->request->param('county_id');
        if($province_id){
            $where['ns.province_id'] = $province_id;
        }
        if($city_id){
            $where['ns.city_id'] = $city_id;
        }
        if($county_id){
            $where['ns.county_id'] = $county_id;
        }
        if($search_name){
            //2023-6-28 lina 修改
            //$where['ns.name'] = ['like','%'.$search_name.'%'];
            $where['ns.name'] = $search_name;
        }
        if($type == 2){ //最新市场
//            $order = 'ns.create_time desc,u.level desc';
            $order = 'ns.refresh_time desc';
        }elseif ($type == 3){ //距离最近
            $order = 'distance,u.level desc,ns.refresh_time desc';
        }else{ //认证企业
//            $order = 'u.level desc,ns.create_time desc';
            $order = 'ns.refresh_time desc';
        }

        if($user_id){
            $where['ns.user_id'] = $user_id;
            $order = 'ns.create_time desc';
        }

        $string = '';
        if($lng && $lat){
            $string = ',(6371 * acos(cos(radians('.$lat.')) * cos(radians(lat)) * cos(radians(lng) - radians('.$lng.')) + sin(radians('.$lat.')) * sin(radians(lat)))) AS distance';
        }
       $model =  (new NurserySell())->alias('ns')
            ->field('ns.id,user_id,ns.name,ns.imgs,ns.introduction,city_id,ns.specs_config,ns.lvl,ns.browse_num,ns.call_num,ns.price,ns.address,ns.create_time,refresh_time,u.nickname,u.avatar,u.level'.$string)
            ->join('user u','ns.user_id = u.id','left')
            ->where($where)
            ->order($order)
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);

        $total = $model->total();
        $list =  $model->items();
        if($list){
            $specsList = (new Specs())->select();
            $nurseryLevel =  \app\common\common\Common::$nurseryLevel;
            $cityList = Server::getInstance()->getAreaList(['level'=>2]); //(['level'=>2]);
            $cityList = array_column($cityList,'name','id');
            foreach ($list as &$v){

                if(!isset($v['distance'])) {
                    $v['distance'] = '-';
                }else{
                    $v['distance'] = round($v['distance'],2);
                }
                $v['img'] = '';
                $v['imgs'] =ImageUtil::handleMore($v['imgs']);
                if(count($v['imgs']) > 0){
                    $v['img'] = ImageUtil::replaceSmall($v['imgs'][0]);
                }
                $v['lvl_name'] = isset($nurseryLevel[$v['lvl']]) ?  $nurseryLevel[$v['lvl']] : '';
                $v['specs_config'] = self::specsConfig($v['specs_config'],$specsList);
                $v['city_name'] = $cityList[$v['city_id']] ??'';
                $v['avatar'] = ImageUtil::handle($v['avatar']);
            }
        }
        $result = array("total" =>$total , "list" => $list);
        $this->success("请求成功", $result);
    }
    /************************** 2023-6-28 lina 新增 start**********************************************************/
    /**
     * 根据名字搜索所有相关的名称
     * */
    public function getNameList(){
        $where = [
            'ns.status'=>'1',
            'u.status'=>'normal'
        ];
        $search_name = $this->request->param('search_name');
        if($search_name){
            $where['ns.name'] = ['like','%'.$search_name.'%'];
        }
        $type = $this->request->param('type',1);
        if($type == 2){ //最新市场
            $order = 'ns.refresh_time desc';
        }elseif ($type == 3){ //距离最近
            $order = 'distance,u.level desc,ns.refresh_time desc';
        }else{ //认证企业
            $order = 'ns.refresh_time desc';
        }

        $user_id = $this->request->param('user_id');
        if($user_id){
            $where['ns.user_id'] = $user_id;
            $order = 'ns.create_time desc';
        }
        $list =  (new NurserySell())->alias('ns')
            ->field('ns.id,user_id,ns.name')
            ->join('user u','ns.user_id = u.id','left')
            ->where($where)
            ->order($order)
            ->select();
        $this->success("请求成功", $list);
    }
    /************************** 2023-6-28 lina 新增 end**********************************************************/

    /**
     * 供应浏览数+1
     */
    public function supplyBrowse()
    {
        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $info =  NurserySell::get($id);
        if(!$info) $this->error("该id不存在");
        $result = NurserySell::update(['browse_num'=>$info['browse_num']+1],['id'=>$id]);
        if(!$result) $this->error("请求失败");
        $userInfo = User::get($info['user_id']);
        $template_num = Cache::get(TEMPLATE3);
        if($userInfo['wechat_openid'] && $userInfo['is_follow'] == 1 && $template_num < 60 && $info['user_id'] != $user['id']){
            $datas=[
                "first"=> "您发布的《".$info['name'].'》正在被用户《'.$user['nickname'].'》查看',
                "keyword1"=> date('Y-m-d H:i:s'),
                "keyword2"=> $info['name'],
                "keyword3"=>$user['mobile'] ? substr_replace($user['mobile'], '*******',4, strlen($user['mobile'])) : '**********',
                "keyword4"=> "您发布的商品正在被查看",
            ];
            Cache::set(TEMPLATE3,$template_num+1,90);
            sendMessage($userInfo['wechat_openid'],$datas,TEMPLATE3);
        }
        $this->success("请求成功");
    }


    /**
     * 供应上传
     */
    public function supplySub()
    {
        $user = $this->auth->getUser();
        if($user['is_nursery_certification'] != 1){
            $info = Companyattestation::get(['user_id'=>$user['id']]);
            if(!$info) $this->error('您还没有提交认证信息');
            if($info){
                if($info['is_pay'] <> 1){
                    $this->error('您还没有缴费');
                }
                if($info['status'] == 0){
                    $this->error('您的认证正在审核中');
                }
                if($info['status'] == 3){
                    $this->error('您的认证审核失败');
                }
            }
        }
        $validate = new \think\Validate([
            ['type_id', 'require', '类型id不能为空'],
            ['type_name', 'require', '类型全名不能为空'],
            ['name', 'require', '苗木名称不能为空'],
//            ['introduction', 'require', '产品简介不能为空'],
            ['lvl', 'require', '苗木等级不能为空'],
            ['phone', 'require', '电话号码不能为空'],
            ['imgs', 'require', '图片不能为空'],
            ['address', 'require', '地址不能为空'],
            ['province_id', 'require', '省份不能为空'],
            ['city_id', 'require', '市不能为空'],
            ['county_id', 'require', '区县不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $name = $this->request->param('name');
        $specs_config = $this->request->param('specs_config');
        $introduction = $this->request->param('introduction');
        $lvl = $this->request->param('lvl');
        $phone = $this->request->param('phone');
        $price = $this->request->param('price',0);
        $address = $this->request->param('address');
        $imgs = $this->request->param('imgs');
        $lng = $this->request->param('lng');
        $lat = $this->request->param('lat');
        $province_id = $this->request->param('province_id');
        $city_id = $this->request->param('city_id');
        $county_id = $this->request->param('county_id');

        if($price < 0){
            $this->error("请输入大于0的数");
        }

        $imgArr = explode(',',$imgs);
        if(count($imgArr)>6){
            $this->error("图片最多上传6张");
        }
        $data=[
            'user_id'=>$user['id'],
            'type_id'=>$this->request->param('type_id'),
            'type_name'=>$this->request->param('type_name'),
            'name'=>$name, //苗木名称
            'imgs'=>$imgs,
            'specs_config'=>$specs_config, //规格配置
            'introduction'=>$introduction, //产品简介
            'lvl'=>$lvl,
            'phone'=>$phone,
            'price'=>$price, //价格
            'address'=>$address, //地址
            'province_id'=>$province_id,
            'city_id'=>$city_id,
            'county_id'=>$county_id,
            'area'=>$this->request->param('area',''),
            'lng'=>$lng,
            'lat'=>$lat,
        ];
        $id = $this->request->param('id');
        if($id){
            $info = NurserySell::update($data,['id'=>$id]);
            if(!$info){
                $this->success("没有更新");
            }
        }else{
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['refresh_time'] = date('Y-m-d H:i:s');
            $info = NurserySell::create($data);
        }
        if($info){
            $this->success("成功");
        }
        $this->error("上传失败");
    }

    /**
     * 我的供应详情
     */
    public function supplySubDetails()
    {
        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $info = NurserySell::get(['user_id'=>$user['id'],'id'=>$id]);
        if($info){
            $info['imgs'] = ImageUtil::handleMore($info['imgs'],false);
            $this->success("获取成功",$info);
        }
        $this->error("不存在");
    }

    /**
     * 我的供应删除
     */
    public function supplySubDel()
    {
        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $info = (new NurserySell)->where(['user_id'=>$user['id'],'id'=>$id])->delete();
        if($info){
            $this->success("删除成功");
        }
        $this->error("删除失败");
    }

    /**
     * @throws \think\exception\DbException
     * 获取电话号码
     */
    public function getPhone()
    {
        $type = $this->request->param('type');
        $id = $this->request->param('id');
        if(!$id || !$type){
            $this->error('参数不全');
        }
        $user = $this->auth->getUser();
        if($type == 1){ //获取供应者的电话
            $info =  NurserySell::get($id);
        }elseif ($type == 2){ //获取求购者的电话
            $info =  Wantbuy::get($id);
        }else{ //获取报价者的电话
            $info =  NurseryWantbuyOffer::get($id);
        }
        if(!$info) $this->error('该数据不存在');

        if($info['user_id'] == $user['id']){  //自己查看自己的电话号码 不需要会员或扣积分
            $this->success('获取成功',['phone'=>$info['phone']]);
        }
        $is_fellow = self::getFellow();
        $userInfo = User::get($info['user_id']);
        if($is_fellow){
            if($type == 1){
                NurserySell::update(['call_num'=>$info['call_num']+1],['id'=>$id]);
            }
            $this->sendTemplateMessage($userInfo,$user);
            $this->success('获取成功',['phone'=>$info['phone']]);
        }

        $Integral = Integral::get(1);
        if($Integral['integral_use']>$user['score']){
            $this->error('你的积分不够');
        }

        $result = User::score(-$Integral['integral_use'],$user['id'],'手机消耗积分');
        if($result){
            if($type == 1){
                NurserySell::update(['call_num'=>$info['call_num']+1],['id'=>$id]);
            }
            $this->sendTemplateMessage($userInfo,$user);
            $this->success('获取成功',['phone'=>$info['phone'],'address'=>$info['address']]);
        }else{
            $this->error('获取失败',$result);
        }
    }

    /**
     * @param $userInfo
     * @param $user
     * 给被查看的人发消息
     */
    private function sendTemplateMessage($userInfo, $user){
        if($userInfo['wechat_openid'] && $userInfo['is_follow'] == 1){
            $datas=[
                "first"=> "您好，收到一条查看电话通知",
                "keyword1"=> $user['nickname'],
                "keyword2"=> date('Y-m-d'),
                "keyword3"=>$user['mobile'] ? substr_replace($user['mobile'], '*******',4, strlen($user['mobile'])) : '**********',
                "keyword4"=> "已获取你的联系方式",
                "remark"=> "请保证电话通畅",
            ];
            sendMessage($userInfo['wechat_openid'],$datas,TEMPLATE2);
        }
    }

    /**
     * @throws \think\exception\DbException
     * 刷新供应列表
     */
    public function refreshSupply(){
        $user = $this->auth->getUser();
        $Confg = \app\admin\model\apply\Confg::get(1);

        if($user['level'] < 1){
            if($user['score'] < $Confg['refurbish_integral']){
                $this->error("您的积分不足，请充值");
            }
        }
        Db::startTrans();
        try {
            User::score(-$Confg['refurbish_integral'],$user['id'],'刷新供应列表消耗'.$Confg['refurbish_integral'].'积分');
            NurserySell::update(['refresh_time'=>date('Y-m-d H:i:s')],['user_id'=>$user['id']]);
            Db::commit();
        } catch (ValidateException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("刷新成功");
    }


    /**
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 判断用户是不是 会员
     */
    private function getFellow(){

        $user = $this->auth->getUser();
        $is_fellow = false;
        if($user['member_expire_time'] >= date('Y-m-d H:i:s')){
            $is_fellow = true;
        }
        if($user['member_expire_time'] && $user['member_expire_time']<date('Y-m-d H:i:s')){
            $user->save(['level'=>0]);
        }
        return $is_fellow;
    }


    /**
     * @param $specsConfig
     * @param $specsList
     * @return array
     * 处理规格配置 数据
     */
    public static function specsConfig($specsConfig , $specsList){
        $specsConfigArr = [];
        if($specsConfig){
           $specsList = array_column($specsList,null,'id');
           $arr = explode(',',$specsConfig);
           if(count($arr) > 0 ){
               foreach ($arr as $v){
                   $arr2 = explode('=',$v);
                   $name = "";
                   $unit = "";
                   $value ="";
                   if(isset($specsList[$arr2[0]])){
                       $name = $specsList[$arr2[0]]['title'];
                       $value = $arr2[1];
                       if($specsList[$arr2[0]]['type'] != 'select'){
                           $unit = $specsList[$arr2[0]]['unit'];
                           $value = $arr2[1];
                       }
                   }
                   $specsConfigArr[]=[
                       'name' => $name,
                       'unit' => $unit,
                       'value' =>  $value
                   ];
               }
           }
        }
        return $specsConfigArr;
    }


}
